/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.mapper.CorpManagementMapper;
import com.koron.scene.domain.SafetyCheck;
import com.koron.scene.domain.SafetyCheckCondition;
import com.koron.scene.mapper.SafetyCheckMapper;
import com.koron.scene.service.api.SafetyCheckService;
import com.koron.scene.utils.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.List;

@Service
public class SafetyCheckServiceImpl implements SafetyCheckService {

    private static final Logger logger = LoggerFactory.getLogger(SafetyCheckServiceImpl.class);
    @Autowired
    private Util util;

    @Override
    public MessageBean<Integer> save(SafetyCheck bean, List<SafetyCheckCondition> safetyCheckConditionList, StaffBean user) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Integer.TYPE);
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isEmpty(bean.getProjectName())) {
                msg.setCode(BusinessCode.PROJECT_NAME_NOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.PROJECT_NAME_NOT_EMPTY.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getInspector()) || StringUtils.isEmpty(bean.getInspectorName())) {
                msg.setCode(BusinessCode.INSPECTOR_NOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.INSPECTOR_NOT_EMPTY.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getInspectedUnit()) || StringUtils.isEmpty(bean.getInspectedUnitName())) {
                msg.setCode(BusinessCode.INSPECTED_UNIT_NOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.INSPECTED_UNIT_NOT_EMPTY.getDescription());
                return msg;
            }
            SafetyCheckMapper mapper = factory.getMapper(SafetyCheckMapper.class);
            if (StringUtils.isEmpty(bean.getId())) {
                bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                bean.setAddTime(bean.getUpdateTime());
                bean.setAddUser(bean.getUpdateUser());
                bean.setAddUserName(bean.getUpdateUserName());
                Integer value = mapper.insert(bean);
                if (value > 0) {
                    for (SafetyCheckCondition safetyCheckCondition : safetyCheckConditionList) {
                        safetyCheckCondition.setId(DefaultIdGenerator.getInstance().generateLongId());
                        safetyCheckCondition.setSafetyCheckId(bean.getId());
                    }
                    value = mapper.batchInsert(safetyCheckConditionList);
                }
                if (value <= 0) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription(BusinessCode.FAILURE.getDescription());
                    return msg;
                }
                factory.close();
                return msg;
            } else {
                SafetyCheck safetyCheck = mapper.queryOne(bean.getId());
                if (null == safetyCheck) {
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription(BusinessCode.FAILURE.getDescription());
                    return msg;
                }
                Integer update = mapper.update(bean);
                if (update > 0) {
                    // 先删除原来的检查整改情况信息
                    mapper.deleteBySafetyCheckId(bean.getId());
                    for (SafetyCheckCondition safetyCheckCondition : safetyCheckConditionList) {
                        safetyCheckCondition.setId(DefaultIdGenerator.getInstance().generateLongId());
                        safetyCheckCondition.setSafetyCheckId(bean.getId());
                    }
                    // 再增加修改后的检查整改情信息
                    update = mapper.batchInsert(safetyCheckConditionList);
                }
                if (update <= 0) {
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription(BusinessCode.FAILURE.getDescription());
                    factory.close(false);
                    return msg;
                }
                factory.close();
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }


    @Override
    public MessageBean<Integer> delete(String id, StaffBean user) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Integer.TYPE);
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
                return msg;
            }
            SafetyCheck safetyCheck = factory.getMapper(SafetyCheckMapper.class).queryOne(id);
            if (null == safetyCheck) {
                msg.setCode(BusinessCode.SAFETY_CHECK_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.SAFETY_CHECK_NOT_EXIST.getDescription());
                return msg;
            }
            Integer delete = factory.getMapper(SafetyCheckMapper.class).delete(id);
            if (delete <= 0) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
                factory.close(false);
                return msg;
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            if (null != factory)
                factory.close(false);
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<SafetyCheck> queryOne(String id) {
        MessageBean<SafetyCheck> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), SafetyCheck.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
                return msg;
            }
            SafetyCheck safetyCheck = factory.getMapper(SafetyCheckMapper.class).queryOne(id);
            if (null == safetyCheck) {
                msg.setCode(BusinessCode.SAFETY_CHECK_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.SAFETY_CHECK_NOT_EXIST.getDescription());
                return msg;
            }
            List<SafetyCheckCondition> safetyCheckConditionList = factory.getMapper(SafetyCheckMapper.class).querySafetyCheckCondition(id);
            safetyCheck.setSafetyCheckConditionList(safetyCheckConditionList);
            msg.setData(safetyCheck);
            factory.close();
            return msg;
        } catch (Exception e) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean> list(String corpCode, String projectName, String startDate, String endDate, Integer start, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            SafetyCheckMapper mapper = factory.getMapper(SafetyCheckMapper.class);
            String codes = util.getDeptCodes(corpCode);
            List<SafetyCheck> list = mapper.queryListByCondition(codes, projectName, startDate, endDate, start, pageSize);
            Integer count = mapper.queryCountByCondition(codes, projectName, startDate, endDate);
            list.forEach(bean->{
                if (StringUtils.isNotEmpty(bean.getCorpCode())){
                    CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(bean.getCorpCode());
                    bean.setCorpName(corpBean == null ? null : corpBean.getCorpName());
                }
            });
            DataBean dataBean = new DataBean();
            dataBean.setTotalNumber(count);
            dataBean.setList(list);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage(count > pageSize ? count % pageSize == 0 ? count / pageSize : count / pageSize + 1 : 1);
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<List> getSafetyCheckCondition() {
        MessageBean<List> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), List.class);
        try (SessionFactory factory = new SessionFactory()) {
            SafetyCheckMapper mapper = factory.getMapper(SafetyCheckMapper.class);
            List<SafetyCheckCondition> list = mapper.getSafetyCheckCondition();
            msg.setData(list);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }
}
